package com.infoland.modules.standardClass.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.axiom.om.OMElement;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.infoland.app.Constants;
import com.infoland.common.util.CniswsUtil;
import com.infoland.common.util.Encodes;
import com.infoland.modules.basic.BaseController;
import com.infoland.modules.basic.Message;
import com.infoland.modules.members.model.ConfirmHistory;
import com.infoland.modules.members.model.UserInfo;
import com.infoland.modules.standardClass.model.SpecialstandarClasses;
import com.infoland.modules.standardClass.service.StandardClassService;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;

import ws.client.WebApi;

public class StandardClassServiceImpl implements StandardClassService {

	/**
	 * 查询所有的专题分类信息
	 * Description 
	 * @param pageNumber 页数
	 * @param pageSize 数据总数
	 * @return 
	 */
	@Override
	public Page<SpecialstandarClasses> findAllList(Integer pageNumber,Integer pageSize) {
		return SpecialstandarClasses.dao.findAllList(pageNumber, pageSize);
	}
	/**
	 * 查询专题目录树集合
	 * Description 
	 * @param pUId 父级标识符
	 * @return 
	 */
	@Override
	public Message findTreeList(String pUId) {
		Message message  = new Message();
		WebApi a = new WebApi();
		OMElement qs = null;
		//接口文档中需要的参数名
		String[] params = new String[] { "orgLoginName", "password", "ukeyId", "orgCode","Uid"};
		//接口中需要的参数值
		String[] paramsValue = new String[] {CniswsUtil.getUserName(),CniswsUtil.getPassword(), "", "",pUId};
		try {
			//调用方法
			qs = a.callMethod(CniswsUtil.getWsdl(),CniswsUtil.getNameSpace(),"getTopicCategoryOfTree",params,paramsValue);
		} catch (Exception e) {
			e.printStackTrace();
			message.setMessage("获取数据时出现异常,请联系管理员!");
		}
		if( StrKit.notBlank(pUId) && qs!=null){
			List<Map<String,Object>> treeList = a.getNodeList(qs);
			if(treeList!=null && treeList.size()>0){
				message.setObject(treeList);
				message.setMessage("获取数据成功!");
				message.setSuccess(Boolean.TRUE);
			}
		}
//		List<SpecialstandarClasses> treeList = new ArrayList<SpecialstandarClasses>();
//		List<TopicCategory> topTreeList = new ArrayList<TopicCategory>();
//		try {
//			//调用获取专题目录树的中标院接口
//			topTreeList = CniswsUtil.getCniswsbasePortType().getTopicCategoryOfTree(CniswsUtil.getUserName(),CniswsUtil.getPassword(), "", "", pUId);
//		} catch (Exception e) {
//			e.printStackTrace();
//			message.setMessage("出现异常,请稍候重试");
//			return message;
//			
//		}
//		if(topTreeList != null  && topTreeList.size()>0){
//			for(TopicCategory top: topTreeList){
//				if(top != null){
//					SpecialstandarClasses specialstandarClasses = new SpecialstandarClasses();
//					// 设置记录表示符
//					specialstandarClasses.setUid(top.getUid().getValue());
//					// 设置专题分类名称
//					specialstandarClasses.setName(top.getName().getValue());
//					// 设置父级标识符
//					specialstandarClasses.setParentUId(top.getParentUid().getValue());
//					treeList.add(specialstandarClasses);
//				}
//			}
//		}
		return message;
	}
	
	/**
	 * 调用接口获取目录树中的具体节点信息
	 * Description 
	 * @return 
	 */
	@Override
	public Message treeNodeList(String pageNumber,String pageSize,String categoryID) {
		Message message  = new Message();
		String s = "";
		String url = "http://www.cssn.net.cn/cssn/frame/cssn/topic_categorycontroller/pageDetails";//调用接口url地址
		Map<String,String> queryParas = new HashMap<String,String>();
		queryParas.put("cgy_uid",categoryID);//参数:二级分类id
		queryParas.put("pageNo",pageNumber);
		queryParas.put("pageSize",pageSize);
		try {
			s = HttpKit.post(url, queryParas, "");
		} catch (Exception e) {
			e.printStackTrace();
			message.setMessage("网络连接超时，请重新点击");
		}
		if(StrKit.notBlank(s)){
			JSONObject object = JSONObject.parseObject(s);
			Integer totalPage = Integer.parseInt(object.getString("totalpage"));
			Integer totalRow = Integer.parseInt(object.getString("total"));
			Integer pageNo = Integer.parseInt(object.getString("pageNo"));
			Integer pageSize1 = Integer.parseInt(object.getString("pageSize"));
			List<Object> rowList = object.getJSONArray("rows");
			if(rowList!=null && rowList.size()>0){
				Page<Object> rowPage = new Page<Object>(rowList, pageNo,pageSize1, totalPage, totalRow);
				message.setObject(rowPage);
				message.setMessage("获取数据成功");
				message.setSuccess(Boolean.TRUE);
			}else{
				message.setMessage("该分类下没有数据");
			}
		}else{
			message.setMessage("网络连接超时，请重新点击");
		}
		return message;
	}
	/**
	 * 调用中标院验证获取用户请求信息接口
	 * Description 
	 * @param standardCodes,url
	 * @return message
	 */
	@Override
	public Message saveValidity(String standardCodes,String userName) {
		Message message  = new Message();
		String confirmResult = "";
		if(StrKit.notBlank(standardCodes)){
			String code = standardCodes.replace("[\"","").replace("\"]","");
			byte[] input = null;
			try {
				input = code.getBytes("UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			String encodedText = Encodes.encodeBase64(input);
			WebApi a = new WebApi();
			/*modified by lihd 20171101 start*/
			String url = "http://www.cssn.net.cn/cssn/frame/piliangyanzheng/shoudong";//调用接口url地址
			//定义调用接口需传的参数变量，同时赋值
			Map<String,String> paramMap = new HashMap<String,String>();
			paramMap.put("info",encodedText);
			//发送post请求，获取有效性确认结果集：confirmResult
			try {
				 confirmResult = HttpKit.post(url, paramMap, "");
			} catch (Exception e) {
				e.printStackTrace();
				message.setMessage("获取数据出现异常,请联系管理员!");
			}
			//s非空则解析返回的 数据，否则返回错误信息
			if(StrKit.notBlank(confirmResult)){
				//定义结果集map重新组装数据返回
				Map<String,Object> resultMap = new HashMap<String,Object>();
				//转换成jsonobject,以json格式获取数据
				JSONObject confirmResultJson = JSONObject.parseObject(confirmResult);
				//获取确认失败数据条数,入结果集resultMap
				resultMap.put("daichuli", confirmResultJson.getString("daichuli"));
				//获取确认成功数据条数，置入结果集resultMap
				resultMap.put("Yichuli", confirmResultJson.getString("Yichuli"));
				List<Object> resultList = confirmResultJson.getJSONArray("list8");
				if(resultList!=null && resultList.size()>0){
					List<Object> list = new ArrayList<Object>();
					Map<String,Record> map = a.getRecord(resultList);
					if(map.keySet() !=null){
						Set<String> set = map.keySet();
						Iterator<String> it = set.iterator();  
						while(it.hasNext()) {  
							list.add(map.get(it.next()));  
						} 
						resultMap.put("list8",list);
					}
				}
				List<Object> newResultList = confirmResultJson.getJSONArray("list9");
				if(newResultList!=null && newResultList.size()>0){
					List<Object> newList = new ArrayList<Object>();
					Map<String,Record> newMap = a.getRecord(newResultList);
					if(newMap.keySet() !=null){
						Set<String> set = newMap.keySet();
						String s = set.toString().replace("[", "").replace("]", "");
						String[] str = s.split(",");
						newList.add(str);
						resultMap.put("list9",newList);
					}
				}
				message.setObject(resultMap);
				message.setMessage("确认成功");
				message.setSuccess(Boolean.TRUE);
			}else{
				message.setMessage("出现异常,请稍候重试");
			}
		}else{
			message.setMessage("标准号为空");
		}

		/*modified by lihd 20171101 end*/
		return message;
	}
	
	
	/**
	 * 导出题录
	 * Description 
	 * @param ukeyId
	 * @param uid
	 * @param tnvOrderValidationItem
	 * @return 
	 */
	@Override
	public void exportValidationItem( @SuppressWarnings("rawtypes") BaseController controller,String userName) {//TNvOrderValidationItem
		Record record = controller.getBean(Record.class,"record");
		//List<Object> text = controller.getJSONArray(record);
		System.out.println(record);
//		if (text != null && text.size()>0) {
//			try {
//				List<String> headerList = Lists.newArrayList();
//				String[] header = { "标准号", "发布单位", "标准名称", "标准状态", "发布日期"};
//				for (String head : header) {
//					headerList.add(head);
//				}
//				String[] attrNames = { "a100", "a102", "a298","a000","a101"};
//				ExportExcel excel = new ExportExcel("", headerList);
//				for (Object o : text) {
//					JSONObject object = (JSONObject) o;
//					Row row = excel.addRow();
//					for (int i = 0; i < attrNames.length; i++) {
//						String column = attrNames[i];
//						excel.addCell(row, i,object.get(column), 2, attrNames.getClass());
//					}
//				}
//				try {
//					excel.write(controller.getResponse(), "有效性确认.xlsx");
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//				excel.dispose();
//				
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
		controller.renderNull();
	}
	
	/**
	 * 导入题录
	 * Description 
	 * @param uploadFile
	 * @return 
	 */
	@Override
	public Message uploadValidationItem(UploadFile uploadFile,Integer userId) {
		Message message = new Message();
		String lineTxt = "";
		List<ConfirmHistory> list = new ArrayList<ConfirmHistory>();
	    try {
	    	//String encoding="GBK"; //考虑到编码格式
	    	if(uploadFile!=null){
	    		File file = uploadFile.getFile();//获取文件
	    		if(file!=null){ //判断文件是否存在
	    			String path = file.getPath();
	    			InputStreamReader read = new InputStreamReader(new FileInputStream(path));
	    			BufferedReader bufferedReader = null;
	    			String fileNameFix = path.substring(path.lastIndexOf(".") + 1, path.length());
	    			if(fileNameFix.equals("txt")){
	    				 bufferedReader = new BufferedReader(read);
	    				if(bufferedReader!=null){
	    					while((lineTxt = bufferedReader.readLine()) != null){
	    						ConfirmHistory c = new ConfirmHistory();
	    						c.setStandardCode(lineTxt);
	    						list.add(c);
	    					}
	    					if(list!=null && list.size()>0){
	    						message.setObject(list);
	    						message.setMessage("读取成功");
	    						message.setSuccess(Boolean.TRUE);
	    					}
	    				}
	    			}
	    			read.close(); 
	    		}else{
	    			message.setMessage("找不到指定的文件");
	    		}
	    	}
	     } catch (Exception e) {
	       message.setMessage("读取文件内容出错");
	       return message;
	     }
		 return message;
	 }
	@Override
	public Message importSuccessValidity(@SuppressWarnings("rawtypes") BaseController controller) {
		Message message = new Message();
		UserInfo userInfo = (UserInfo) controller.getSession().getAttribute(Constants.SESSION_NAME);
		JSONArray json = controller.getJSONArray("record");
		if(json!=null && json.size()>0){
			for(int i = 0;i<json.size();i++){
				JSONObject object = (JSONObject) json.get(i);
				ConfirmHistory con = new ConfirmHistory();
				con.setStandardCode(object.get("a100").toString());
				con.setStandardName(object.get("a298").toString());
				con.setOperateResult(0);
				con.setOperateResultV("成功");
				con.setOperateTime(new Date());
				con.setUserInfoId(userInfo.getId());
				con.setUserName(userInfo.getUserName());
				if(con.save()){
					message.setMessage("导入成功");
					message.setSuccess(Boolean.TRUE);
				}else{
					message.setMessage("没有相关数据返回");
				}
			}
		}else{
			message.setMessage("没有相关数据返回");
		}
		 return message;
}
	@Override
	public Message importFailValidity(@SuppressWarnings("rawtypes") BaseController controller) {
		Message message = new Message();
		UserInfo userInfo = (UserInfo) controller.getSession().getAttribute(Constants.SESSION_NAME);
		JSONArray json = controller.getJSONArray("record");
		System.out.println(json);
		if(json!=null && json.size()>0){
			for(int i=0;i<json.size();i++){
				ConfirmHistory con = new ConfirmHistory();
				con.setStandardCode(json.getString(i));
				con.setOperateResult(1);
				con.setOperateResultV("失败");
				con.setOperateTime(new Date());
				con.setUserInfoId(userInfo.getId());
				con.setUserName(userInfo.getUserName());
				if(con.save()){
					message.setMessage("导入成功");
					message.setSuccess(Boolean.TRUE);
				}else{
					message.setMessage("没有相关数据返回");
				}
			}
			
		}else{
			message.setMessage("没有相关数据返回");
		}
		 return message;
	}
}
